﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.RBAC;
using RBAC.Api.Read.Dto;

namespace RBAC.Api.Read.CommandHandler.RBAC
{
    public class GetUserCommandHandler : IRequestHandler<GetUserCommand, APIResult<APIPagin<UserDto>>>
    {
        private readonly IBaseRepositry<User> dal;
        private readonly IBaseRepositry<Role> dal2;
        private readonly IBaseRepositry<UserRole> dal3;
        private readonly IMapper mapper;

        public GetUserCommandHandler(IBaseRepositry<User> baseRepositry,
                                     IBaseRepositry<Role> baseRepositry1,
                                     IBaseRepositry<UserRole> baseRepositry2,
                                     IMapper mapper)
        {
            dal = baseRepositry;
            dal2 = baseRepositry1;
            dal3 = baseRepositry2;
            this.mapper = mapper;
        }
        public Task<APIResult<APIPagin<UserDto>>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPagin<UserDto>> result = new APIResult<APIPagin<UserDto>>();
            result.Code = ResultCode.Success;
            result.Message = "查询成功";

            //获取用户列表
            var list = dal.GetAll().AsTracking();

            //模糊查询
            if (!string.IsNullOrEmpty(request.Name))
            {
                list = list.Where(x => x.Username.Contains(request.Name));
            }
            var usrDto = mapper.Map<List<UserDto>>(list);

            var totalCount = list.Count();
            var page = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            usrDto = usrDto.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            foreach (var item in usrDto)
            {
                //获取角色id
                var roleId = dal3.GetAll().
                    Where(x => x.UserId == item.Id).
                    Select(x => x.RoleId).ToList();
                item.RoleId = roleId;
                //获取角色名称
                var roleName = dal2.GetAll()
                    .Where(x => roleId.Contains(x.Id))
                    .Select(x => x.RoleName).ToList();
                item.RoleName = string.Join(",", roleName);
            }

            APIPagin<UserDto> res = new APIPagin<UserDto>()
            {
                TotaleCount = totalCount,
                PageCount = page,
                List = usrDto
            };

            result.Data = res;

            return Task.FromResult(result);
        }
    }
}
